//
//  QKSegmentView.m
//  Gigle
//
//  Created by 丁乾坤 on 2016/10/21.
//  Copyright © 2016年 丁乾坤. All rights reserved.
//

#import "QKSegmentView.h"
#import "QKTitleButton.h"

typedef void(^SegmentSelectIndex)(NSInteger, NSString *);

@interface  QKSegmentView()

@property(nonatomic, strong)NSArray *titles;

@property(nonatomic, copy)SegmentSelectIndex segmentSelectIndex;

@property(nonatomic, strong)UIButton *selectedButton;

@end

@implementation QKSegmentView

static QKSegmentView *segmentView;

+(instancetype)qk_segmentWithTitleArray:(NSArray *)titles segmentSelectIndex:(void(^)(NSInteger, NSString *))blockSelectIndex{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        segmentView = [[QKSegmentView alloc] init];
    });
    segmentView.titles = titles;
    segmentView.segmentSelectIndex = blockSelectIndex;
    return segmentView;
}


- (void)setTitles:(NSArray *)titles{
    _titles = titles;
    NSInteger count = titles.count;

    CGFloat buttonWidth = SWIDTH / count;
    CGFloat buttonHeight = 38.f;
    CGFloat fontNormal = 14;
    for (int i = 0; i < count; i++) {
        NSString *title = titles[i];
        QKTitleButton *button = [QKTitleButton buttonWithType:UIButtonTypeSystem];
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        button.tag = 200 + i;
        [button setTitle:title forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:fontNormal];
        button.frame = CGRectMake(i * buttonWidth, 0, buttonWidth, buttonHeight);
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateFocused];
        if (i == 0) {  //默认被选中
            [self changeFontSize:button];
        }
        [self addSubview:button];
        
    }
}
#pragma mark ---单击事件
- (void)buttonAction:(UIButton *)button{
    NSInteger index = button.tag - 200;
    NSString *title = button.currentTitle;
    [self changeFontSize:button];
    segmentView.segmentSelectIndex(index, title);
}

#pragma mark ---- 改变选中字体的大小
- (void)changeFontSize:(UIButton *)button{
    if (self.selectedButton) {
        self.selectedButton.titleLabel.font = [UIFont systemFontOfSize:14];
    }
    button.titleLabel.font = [UIFont systemFontOfSize:17];
    self.selectedButton = button;
}


@end
